package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkd.entity.Node;
import com.lkd.entity.Region;
import com.lkd.mapper.NodeMapper;
import com.lkd.mapper.RegionMapper;
import com.lkd.service.RegionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.vo.PageBean;
import com.lkd.vo.RegionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 运营区域 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-20
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {

    @Autowired
    private NodeMapper nodeMapper;

    @Override
    public PageBean<RegionVo> search(String name, Integer pageIndex, Integer pageSize) {
        Page<Region> page=new Page<>(pageIndex,pageSize);

        LambdaQueryWrapper<Region> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(name),Region::getName,name);
        page = getBaseMapper().selectPage(page,wrapper);

        List<RegionVo>regionVoList=page.getRecords().stream().map(region -> {
            RegionVo regionVo = BeanUtil.copyProperties(region,RegionVo.class);

            LambdaQueryWrapper<Node> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(Node::getRegionId,region.getId());
            regionVo.setNodeCount(nodeMapper.selectList(wrapper1).size());
            return regionVo;
        }).collect(Collectors.toList());

        return new PageBean<>(page,regionVoList);
    }
}
